import { sp, sys, tween, Tween } from "cc";

export default class Utils {


    static delay(timeSecond: number): Promise<void> {
        return new Promise<void>(resolve => {
            setTimeout(() => {
                resolve()
            }, timeSecond * 1000)
        })
    }

    /**通过action延时 */
    static delayAction(timeSecond: number, target?: any): Promise<void> {
        return new Promise<void>(resolve => {
            tween(target || this).delay(timeSecond).call(() => {
                resolve();
            }).start();
        })
    }

    static schedule(interval: number, times: number, callback: Function) {
        if (times <= 1) {
            callback()
            return
        }
        let count = 0
        let timer = setInterval(function () {
            callback()
            if (++count >= times) {
                clearInterval(timer)
            }
        }, interval * 1000)
    }

    static gc() {
        if (sys.isNative) {
            sys.garbageCollect();            
        }
    }

    /**异步方式执行tween,方便链式调用 */
    static startTweenAsync(tween: Tween<any>): Promise<void> {
        return new Promise<void>((resolve, reject) => {
            tween.call(() => {
                resolve();
            }).start()
        })
    }

}